package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Department;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.qo.EmployeeQueryObject;
import cn.wolfcode.crm.qo.JsonResult;
import cn.wolfcode.crm.service.IDepartmentService;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IRoleService roleService;

    @RequestMapping("/list")
    //@RequiresPermissions("employee:list")
    public String list(Model model, @ModelAttribute("qo") EmployeeQueryObject qo) {
        PageInfo<Employee> pageResult = employeeService.query(qo);
        List<Department> departments = departmentService.listAll();
        model.addAttribute("depts", departments);
        model.addAttribute("result", pageResult);
        return "/employee/list";
    }

    @RequestMapping("/delete")
    @RequiresPermissions(value = {"employee:delete", "员工删除"}, logical = Logical.OR)
    @ResponseBody
    public JsonResult delete(Long id) {
        try {
            if (id != null) {
                employeeService.delete(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "操作失败");

        }
        return new JsonResult(true, "操作成功");
    }

    @RequestMapping("/input")
    public String input(Model model, Long id) {
        List<Department> departments = departmentService.listAll();
        List<Role> roles = roleService.listAll();
        model.addAttribute("roles", roles);
        model.addAttribute("departments", departments);
        if (id == null) {
            return "/employee/input";
        } else {
            Employee employee = employeeService.selectOne(id);
            model.addAttribute("employee", employee);
            return "/employee/input";
        }
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Employee employee, Long[] ids) {

        if (employee.getId() == null) {
            Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName());
            employee.setPassword(md5Hash.toHex());
            employeeService.save(employee, ids);

        } else {
            employeeService.update(employee, ids);
        }

        return new JsonResult(true, "操作成功");
    }

    @RequestMapping("/batchDelete")
    @ResponseBody
    public JsonResult batchDelete(Long[] ids) {
        if (ids != null && ids.length > 0) {
                /*for (Long id : ids) {
                    employeeService.delete(id);
                }*/
            employeeService.batchDelete(ids);
        }

        return new JsonResult(true, "操作成功");


    }

    /**
     * true验证通过
     * false验证不通过
     *
     * @param name
     * @return
     */
    @RequestMapping("/checkName")
    @ResponseBody
    public Map checkName(String name, Long id) {

        Employee employee = employeeService.selectByName(name);
        HashMap<String, Object> map = new HashMap<>();
        if (employee != null && employee.getId() != id) {
            map.put("valid", false);
            return map;
        }
        map.put("valid", true);

        return map;
    }

    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse resp) throws IOException {
        //文件下载的响应头
        resp.setHeader("Content-Disposition", "attachment;filename=employee.xls");
        Workbook wk = employeeService.exportXls();

        wk.write(resp.getOutputStream());

    }

    @RequestMapping("/importXls")
    @ResponseBody
    public JsonResult importXls(MultipartFile file) throws IOException {
        employeeService.importXls(file);
        return new JsonResult(true, "导入成功");
    }

    @RequestMapping("/changePassword")
    public String changePassword(Model model) {
        Subject subject = SecurityUtils.getSubject();
        Employee employee = (Employee) subject.getPrincipal();
        model.addAttribute("id", employee.getId());
        return "/changePassword/cp";

    }

    @RequestMapping("/updatePw")
    @ResponseBody
    public Map updatePw(Long id, String srcPassword) {
        HashMap<String, Object> map = new HashMap<>();
        Employee employee = employeeService.selectOne(id);
        Md5Hash md5Hash = new Md5Hash(srcPassword, employee.getName());
        map.put("valid", employee.getPassword().equals(md5Hash.toString()));
        return map;
    }

    @RequestMapping("/updatePassword")
    public String updatePassword(Long id, String newPassword) {

        Md5Hash md5Hash = new Md5Hash(newPassword, employeeService.selectOne(id).getName());
        employeeService.updatePw(id, md5Hash.toHex());
        return "redirect:/employee/list.do";
    }

    @RequestMapping("/changeStatus")
    @ResponseBody
    public JsonResult changeStatus(Long id) {
        employeeService.changeStatus(id);
        return new JsonResult(true, "操作成功");
    }


}
